//
//  ProposeNewEventViewController.m
//  SecretRoom
//
//  Created by Sitdhibhong Laokok on 9/4/54 BE.
//  Copyright 2554 App Tree. All rights reserved.
//

#import "ProposeNewEventViewController.h"

#import "EventDatetimePickerViewController.h"
#import "EventLocationAnnotation.h"
#import "EventDescriptionByTagsViewController.h"
#import "EventInvitationListViewController.h"

#import "Event.h"

@interface ProposeNewEventViewController()
- (id)createEventWithLocalRepositoryAndSecretRoom;
- (void)updateLocation;
@end

@implementation ProposeNewEventViewController

@synthesize context;
@synthesize dateFormatter=_dateFormatter;

@synthesize eventName;
@synthesize eventTimestamp=_eventTimestamp;
@synthesize locationCoordinate=_locationCoordinate;
@synthesize invitees;
@synthesize tagsForThisEvent;
@synthesize locationManager=_locationManager;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithStyle:(UITableViewStyle)style withContext:(NSManagedObjectContext *)ct
{
    self = [super initWithStyle:style];
    if (self) {
        self.context = ct;
    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIBarButtonItem *cancelBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelProposeNewEventButtonClicked)];
    UIBarButtonItem *doneBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(saveProposeNewEventButtonClicked)];
    
    self.navigationItem.leftBarButtonItem = cancelBarButton;
    self.navigationItem.rightBarButtonItem = doneBarButton;
    
    _dateFormatter = [[NSDateFormatter alloc] init];
    _dateFormatter.locale = [NSLocale currentLocale];
    _dateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"yyyyMMMdd HHmm" options:0 locale:[NSLocale currentLocale]];
    _dateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"yyyyMMMdd HHmm" options:0 locale:[NSLocale currentLocale]];
    _dateFormatter.timeZone = [NSTimeZone systemTimeZone];
    
    _eventTimestamp = [[NSDate date] retain];
    
    NSLog(@"datetime format: %@", _dateFormatter.dateFormat);
    
    gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
//    gregorian.locale = [NSLocale currentLocale];

    eventNameField = [[UITextField alloc] initWithFrame:CGRectMake(35, 12, 250, 34)];
    eventNameField.placeholder = @"Event name";
    eventNameField.textAlignment = UITextAlignmentCenter;
    eventNameField.tag = 100;
    eventNameField.delegate = self;
    
    noteForEventView = [[UITextView alloc] initWithFrame:CGRectMake(15, 5, 290, 140)];
    noteForEventView.font = [UIFont fontWithName:@"Helvetica" size:17.0];
    noteForEventView.tag = 200;
    
    eventMapView = [[MKMapView alloc] initWithFrame:CGRectMake(10, 0, 300, 150)];
    eventMapView.delegate = self;
    eventMapView.layer.cornerRadius = 10;
    eventMapView.showsUserLocation = YES;
    eventMapView.tag = 300;
    
    UILongPressGestureRecognizer *longTimesGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longtimePressedToDropPinOnEventLocationMap:)];
    longTimesGesture.minimumPressDuration = 2.0;
    [eventMapView addGestureRecognizer:longTimesGesture];
    [longTimesGesture release];
    
    [cancelBarButton release];
    [doneBarButton release];
    
    self.title = @"Create Event";
    
    isUserLocation = YES;
    
//    [self.locationManager startUpdatingLocation];
    
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

- (void)viewDidUnload
{
    [eventMapView removeAnnotations:[eventMapView annotations]];
    [self.locationManager stopUpdatingLocation];
    
    [self setDateFormatter:nil];
    
    [eventNameField release];
    eventNameField = nil;
    
    [noteForEventView release];
    noteForEventView = nil;
    
    [eventMapView release]; 
    eventMapView = nil;
    
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSLog(@"will appear");
    dateComponents = [[gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:self.eventTimestamp] retain];

    [self.tableView reloadData];

    [self updateLocation];
    
    NSLog(@"Will appear again");
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"did appear");
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.tableView reloadData];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc
{
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [context release];
    [eventMapView release];
    [locationManager release];
    
    [eventName release];
    [_eventTimestamp release];
    [invitees release];
    [tagsForThisEvent release];
    
    [_dateFormatter release];
    
    [dateComponents release];
    [gregorian release];
    
    // Control
    [eventNameField release];
    [noteForEventView release];
    
    [super dealloc];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // event name, note, location, date, tags, invitees
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        id o = [cell viewWithTag:100];
        if (o != nil) {
            [o removeFromSuperview];
        }
        
        cell.textLabel.text = @"";
        cell.detailTextLabel.text = @"";
    }
    
    // Configure the cell...

    if (indexPath.section == 0) {
        // Event Name
        [cell addSubview:eventNameField];
    } else if (indexPath.section == 1) {
        // event note
        cell.accessoryType = UITableViewCellAccessoryNone;
        [cell addSubview:noteForEventView];
    } else if (indexPath.section == 2) {
        // map 
        [cell addSubview:eventMapView];
    } else if (indexPath.section == 3) {
        // date
        
        NSLog(@"components: %@", [gregorian dateFromComponents:dateComponents]);

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.text = [self.dateFormatter stringFromDate:[gregorian dateFromComponents:dateComponents]];
        
        NSLog(@"Date %@", [self.dateFormatter stringFromDate:[gregorian dateFromComponents:dateComponents]]);
    } else if (indexPath.section == 4) {
        // tags
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"Tags";
    } else if (indexPath.section == 5) {
        // invitees
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"Invitations";
    }
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 3) {
        EventDatetimePickerViewController *edpv = [[[EventDatetimePickerViewController alloc] initWithNibName:@"EventDatetimePickerViewController" bundle:nil] autorelease];
        
        edpv.delegate = self;
        edpv.dateFormatter = self.dateFormatter;
        edpv.dateComponents = dateComponents;
        edpv.calendar = gregorian;
        
        [self.navigationController pushViewController:edpv animated:YES];
        
//        [edpv release];
        
    } else if (indexPath.section == 4) {
        EventDescriptionByTagsViewController *edbtvc = [[[EventDescriptionByTagsViewController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
        
        [self.navigationController pushViewController:edbtvc animated:YES];
        
//        [edbtvc release];
    } else if (indexPath.section == 5) {
        EventInvitationListViewController *eilvc = [[[EventInvitationListViewController alloc] initWithNibName:@"EventInvitationListViewController" bundle:nil] autorelease];
        
        eilvc.delegate = self;
        
        [self.navigationController pushViewController:eilvc animated:YES];
        
//        [eilvc release];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (indexPath.section == 1 || indexPath.section == 2) ? 150 : 44 ;
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Error while retrieve location: %@", [error localizedDescription]);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"New location: %f", newLocation.coordinate.latitude);
}

#pragma mark - MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    MKAnnotationView *annotation = [views lastObject];
    
    if (!isUserLocation) {
        // This is not user location
        CGRect endFrame = annotation.frame;
        annotation.frame = CGRectMake(
                                      annotation.frame.origin.x, 
                                      annotation.frame.origin.y - 230, 
                                      annotation.frame.size.width, 
                                      annotation.frame.size.height
                                      );
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.45];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        
        annotation.frame = endFrame;
        
        [UIView commitAnimations];
        
    }
    
    id<MKAnnotation> mp = [annotation annotation];
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate], 2000, 2000);
    
    self.locationCoordinate = [mp coordinate];
    
    [mapView setRegion:region animated:YES];
    [eventMapView reloadInputViews];
    
    NSLog(@"Location: latitude %f, longitude %f", self.locationCoordinate.latitude, self.locationCoordinate.longitude);
}

#pragma mark - Custom method
- (void)cancelProposeNewEventButtonClicked
{
    // clear message
    
    [self dismissModalViewControllerAnimated:YES];
}

- (void)saveProposeNewEventButtonClicked
{
    [self performSelectorOnMainThread:@selector(createEventWithLocalRepositoryAndSecretRoom) 
                           withObject:nil 
                        waitUntilDone:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self dismissModalViewControllerAnimated:YES];
    

}

- (id)createEventWithLocalRepositoryAndSecretRoom
{
    NSLog(@"Context: %@", self.context);
    
    Event *event = [[Event alloc] initWithEntity:[NSEntityDescription entityForName:@"Event" inManagedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext]] 
                  insertIntoManagedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext]];
    
    event.eventName = eventNameField.text;
    event.eventTimestamp = [SLCommonsDateUtility localDateToGMTDate:self.eventTimestamp];
    event.hasTags = [NSSet setWithArray:self.tagsForThisEvent];
    event.latitude = [NSString stringWithFormat:@"%f", self.locationCoordinate.latitude];
    event.longitude = [NSString stringWithFormat:@"%f", self.locationCoordinate.longitude];
    event.isArchived = [NSNumber numberWithBool:NO];
    event.invitees = [NSSet setWithArray:self.invitees];
    event.keyImage = nil;
    event.note = noteForEventView.text;
    event.evidences = nil;
    
    event.invitees = [NSSet setWithArray:self.invitees];
    
    
    NSError *error = nil;
    [[[SRConnectionControlCenter sharedInstance] manageObjectContext] save:&error];
    if (error != nil) {
        NSLog(@"Error : %@", [error localizedDescription]);
        [error release];
    }
    
    [event release];
    return nil;
}

- (NSDate *)eventTimestamp
{
    if (_eventTimestamp == nil) {
        _eventTimestamp = [NSDate date];
    }
    
    return _eventTimestamp;
}

- (CLLocationManager *)locationManager
{
    if (_locationManager != nil) {
        return _locationManager;
    }
    
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.distanceFilter = kCLHeadingFilterNone;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    return _locationManager;
}

- (void)longtimePressedToDropPinOnEventLocationMap:(UILongPressGestureRecognizer *)gesture
{
    NSLog(@"Long pressed");
    if (gesture.state != UIGestureRecognizerStateBegan)
        return;
    
    CGPoint touchPoint = [gesture locationInView:eventMapView];
    CLLocationCoordinate2D touchMapToCoordinate = [eventMapView convertPoint:touchPoint toCoordinateFromView:eventMapView];
    
    [eventMapView removeAnnotations:[eventMapView annotations]];
    
    [eventMapView addAnnotation:[EventLocationAnnotation eventLocationAnnotationWithCoordinate:touchMapToCoordinate 
                                                                                          name:self.eventName 
                                                                                        detail:nil]];
}

- (void)updateLocation
{
    [self.locationManager startUpdatingHeading];
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([textField.text length] > 0) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }
}

@end
